<?php

namespace app\common\model;

use app\common\logic\FieldKey;
use app\common\serve\WjzxBorrow;
use think\Db;
use think\Request;

/**
 * 标的
 * Class BorrowInfo
 * @package app\common\model
 */
class Borrow extends Base
{
    protected $table = 'borrow';

    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    protected $auto = array('update_time');
    protected $insert = array('create_time');

    protected $type = array(
        'id' => 'integer',
//        'cover_id'   => 'integer',
    );


    public $repayment_type = [
        1 => '一次性还本付息',
        2 => '分期还本息',
        3 => '等额本息',
        4 => '等额本金'
    ];

    /**
     * 是否新手标
     * @var array
     */
    public $is_new = [
        2 => '否',
        1 => '是',
    ];

    /**
     * 是否发布
     * @var array
     */
    public $is_publish = [
        1 => '是',
        2 => '否',
    ];
    /**
     *
     * //        array('name'=>'cover_id', 'title'=>'广告图片', 'type'=>'image', 'help'=>'', 'option'=>''),
     * //        array('name'=>'url', 'title'=>'广告链接', 'type'=>'text', 'help'=>'', 'option'=>''),
     *
     * //        array('name'=>'photolist', 'title'=>'辅助图片', 'type'=>'images', 'help'=>'', 'option'=>''),
     *
     * //        array('name'=>'listurl', 'title'=>'辅助链接', 'type'=>'textarea', 'help'=>'对应辅助图片的排序，一行一个', 'option'=>''),
     * //        array('name'=>'background', 'title'=>'广告背景颜色', 'type'=>'text', 'help'=>'', 'option'=>''),
     * //        array('name'=>'content', 'title'=>'广告描述', 'type'=>'textarea', 'help'=>'', 'option'=>''),
     * //        array('name'=>'status', 'title'=>'状态', 'type'=>'select', 'help'=>'', 'option'=>array('1'=>'开启','0'=>'禁用')),
     *
     * //        array('name'=>'info', 'title'=>'详细描述', 'type'=>'text', 'help'=>'', 'option'=>''),
     *
     * //        array('name'=>'place_id', 'title'=>'PLACE_ID', 'type'=>'hidden', 'help'=>'', 'option'=>''),
     * //        array('name'=>'img', 'title'=>'文件资料', 'type'=>'text', 'help'=>'', 'option'=>''),
     * 列表
     * @var array
     */
    public $keyList = [
        ['name' => 'id', 'title' => 'ID', 'type' => 'hidden', 'help' => '', 'option' => ''],
        ['name' => 'borrow_name', 'title' => '名称', 'type' => 'text', 'help' => '', 'option' => ''],
        ['name' => 'borrow_duration', 'title' => '期限(天)', 'type' => 'text', 'help' => '', 'option' => ''],
        ['name' => 'borrow_interest_rate', 'title' => '日化率', 'type' => 'text', 'help' => '', 'option' => ''],
        ['name' => 'borrow_prepay_rate', 'title' => '预付款比例', 'type' => 'text', 'help' => '', 'option' => ''],
        ['name' => 'borrow_min', 'title' => '最低购买金额', 'type' => 'text', 'help' => '', 'option' => ''],
        ['name' => 'cover_id', 'title' => '图片', 'type' => 'image', 'help' => '', 'option' => ''],
        ['name' => 'info', 'title' => '产品描述', 'type' => 'textarea', 'help' => '', 'option' => ''],
        ['name' => 'is_publish', 'title' => '是否发布', 'type' => 'select', 'help' => '', 'option' => ''],

//        ['name' => 'borrow_money', 'title' => '产品总金额', 'type' => 'text', 'help' => '', 'option' => ''],
//        ['name' => 'repayment_type', 'title' => '产品还款方式', 'type' => 'select', 'help' => '', 'option' => []],
//        ['name' => 'borrow_max', 'title' => '最大投标金额', 'type' => 'text', 'help' => '', 'option' => ''],
//        ['name' => 'is_new', 'title' => '新手标', 'type' => 'select', 'help' => '', 'option' => ''],
//        ['name' => 'img_list', 'title' => '产品资料图片', 'type' => 'images', 'help' => '', 'option' => ''],

    ];

    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        foreach ($this->keyList as $key => $value) {
//            if ($value['name'] == 'repayment_type') {
//                $value['option'] = $this->repayment_type;
//            }
//            if ($value['name'] == 'is_new') {
//                $value['option'] = $this->is_new;
//            }
            if ($value['name'] == 'is_publish') {
                $value['option'] = $this->is_publish;
            }

            $this->keyList[$key] = $value;
        }
    }

    /**
     * @param array $where
     * @param bool|true $field
     * @param string $order
     * @param int $page
     * @param int $limit
     * @return array
     */
    public function getBorrowList($where = [], $field = true, $order = '', $page = 0, $limit = 20)
    {
        $order = !empty($order) ? $order : $this->getPk() . ' DESC';
        $data = $this->field($field)->where($where)->order($order)->page($page, $limit)->select();
        return $this->parseResult($data);
    }

    /**
     * @param array $where
     * @param bool|true $field
     * @param string $order
     * @param int $page
     * @param int $limit
     * @return array
     */
    public function getBorrowTpsList($where = [], $field = true, $order = '', $page = 0, $limit = 20)
    {
        $order = !empty($order) ? $order : $this->getPk() . ' DESC';
        $data = $this->field($field)->where($where)->order($order)->page($page, $limit)->select();

        //判断当前是否还存在可投推荐标的
        $count = Db::name('borrow_info')->where(['borrow_status' => 2, 'borrow_tps' => 3, 'product_type' => ['not in', [6]], 'is_publish' => 1])->count();
        if ($count < 1) {
            $id = Db::name('borrow_info')->where(['borrow_status' => 2, 'borrow_tps' => 1, 'product_type' => ['not in', [6]], 'is_publish' => 1])->order('cash_borrow asc')->value('id');
            if ($id > 0) {
                Db::name('borrow_info')->where(['id' => $id])->update(['borrow_tps' => 3,]);
                $data = $this->field($field)->where($where)->order($order)->page($page, $limit)->select();
            }
        }

        return $this->parseResult($data);
    }

    /**
     * @param array $where
     * @param bool|true $field
     * @param string $order
     * @param int $limit
     * @param bool|false $isMobile
     * @return array
     */
    public function getBorrowListByPage($where = [], $field = true, $order = '', $limit = 20, $isMobile = false)
    {
        $order = !empty($order) ? $order : $this->getPk() . ' DESC';

        $data = $this->field($field)->alias('borrow')->where($where)->order($order)->paginate($limit, $isMobile, ['query' => Request::instance()->param()]);
        $data = $this->parseResult($data);

        return $data;
    }

    /**
     * @describe 获取数据集 标的列表导出   borrow
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int $limit
     * @return $this
     */
    public function getBorrowCollect($where = [], $field = true, $order = '', $limit = 20)
    {
        $order = !empty($order) ? $order : 'borrow.id DESC';
        return $this->alias('borrow')
            ->join('__MEMBERS__ m', 'm.id=borrow.borrow_uid', 'left')->field($field)->where($where)->order($order);
    }

    /**
     * 获取标的信息
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int $limit
     * @return array|\think\Paginator
     */
    function getNewBorrowListByPage($where = [], $field = true, $order = '', $limit = 20)
    {
        $order = !empty($order) ? $order : $this->getPk() . ' DESC';

        $data = $this->field($field)->alias('borrow')->where($where)->order($order)
            ->paginate($limit, '', ['query' => Request::instance()->param()]);

        foreach ($data as $k => $v) {
            $v['first_verify_time'] = $v['first_verify_time'] > 0 ? date('Y-m-d H:i:s', $v['first_verify_time']) : '';
            $v['second_verify_time'] = $v['second_verify_time'] > 0 ? date('Y-m-d H:i:s', $v['second_verify_time']) : '';
            $v['deadline'] = $v['deadline'] > 0 ? date('Y-m-d', $v['deadline']) : '';
            $data->offsetSet($k, $v);
        }
        return $data;
    }

    /**
     * 总金额
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int $limit
     * @return array|\think\Paginator
     */
    function getNewBorrowMoney($where = [])
    {
        return $this->alias('borrow')->where($where)->sum('borrow_money');
    }

    /**
     * 总金额
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int $limit
     * @return array|\think\Paginator
     */
    function getValidBorrowMoney($where = [])
    {
        if (isset($where['borrow.borrow_status'])) {
            unset($where['borrow.borrow_status']);
        }

        $where['borrow.borrow_status'] = ['in', [6, 7, 8, 9, 10]];
        return $this->alias('borrow')->where($where)->sum('borrow_money');
    }

    //获取标的汇总列表
    public function getBorrowGatherInfo($where, $field)
    {
        return Db::name('borrow_info')->alias('b')
            ->field($field)
            ->join('__BORROW_INVESTOR__ bi', 'b.id = bi.borrow_id', 'LEFT')
            ->join('__MEMBERS__ m', 'm.id = b.borrow_uid', 'LEFT')
            ->join('__MEMBER_INFO__ mi', 'mi.uid = b.borrow_uid', 'LEFT')
            ->where(array_merge($where, ['bi.status' => ['IN', '1,4,5']]))
            ->group('b.id')
            ->order('b.id DESC');
    }

    /**
     * 取得标的汇总
     * @param array $where
     * @param bool|true $field
     * @param string $group
     * @param string $order
     * @param int $limit
     * @return array|\think\Paginator
     */
    public function getBorrowInfoByGroup($where = [], $field = true, $group = '', $order = '', $limit = 20, $isMobile = false)
    {
        $order = !empty($order) ? $order : $this->getPk() . ' DESC';

        $data = $this->field($field)->where($where)->order($order)->group($group)->paginate($limit, $isMobile, ['query' => Request::instance()->param()]);

        $data = $this->parseResult($data);

        return $data;
    }

    /**
     * 取得还款方式 - 中文名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getRepaymentTypeNameAttr($value, $data)
    {
        return isset(FieldKey::$borrow_info_repayment_type[$data['repayment_type']]) ? FieldKey::$borrow_info_repayment_type[$data['repayment_type']] : '';
    }

    /**
     * 取得标的状态 - 中文名
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getBorrowStatusNameAttr($value, $data)
    {
        if (isset(FieldKey::$borrow_info_borrow_status[$data['borrow_status']])) {
            if ($data['borrow_status'] == 2 && $data['is_publish'] == 2) {
                return '初审通过，未发布';
            }

            return FieldKey::$borrow_info_borrow_status[$data['borrow_status']];
        } else {
            return '';
        }
    }

    /**
     * 取得产品类型 - 中文名
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getProductTypeNameAttr($value, $data)
    {
        return isset(FieldKey::$borrow_product_old_show_type[$data['product_type']]) > 0 ? FieldKey::$borrow_product_old_show_type[$data['product_type']] : '';
    }

    /**
     * 取得是否新手标 - 中文名
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getBorrowTpsNameAttr($value, $data)
    {
        return isset(FieldKey::$borrow_info_borrow_tps[$data['borrow_tps']]) ? FieldKey::$borrow_info_borrow_tps[$data['borrow_tps']] : '';
    }

    /**
     * 取得还款方式 - 中文名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getBorrowTypeNameAttr($value, $data)
    {
        return isset(FieldKey::$borrow_info_borrow_type[$data['borrow_type']]) ? FieldKey::$borrow_info_borrow_type[$data['borrow_type']] : '';
    }

    /**
     * 解析结果
     * @param array $data
     * @return array
     */
    public function parseResult($data = [])
    {
        if (count($data, 1) > 0) {
            foreach ($data as $k => $v) {
                //是否显示加息特权

                $status = 0;
                if (($v['id'] >= 3291 && $v['id'] <= 3306 && $v['product_type'] != 6) || $v['borrow_tps'] == 3) $status = 2;
                $data[$k]['new_user_privilege'] = $status;

                if (isset($v['product_type']) && !empty($v['product_type'])) {
                    if ($v['borrow_tps'] == 2) {
                        $data[$k]['borrow_name'] = '新手标 NO.' . $v['id'];
                    } else {
                        $product_type = isset(FieldKey::$borrow_info_product_type[$v['product_type']]) ? FieldKey::$borrow_info_product_type[$v['product_type']] : '';
                        $data[$k]['borrow_name'] = '微 · ' . $product_type . ' NO.' . $v['id'];
                    }
                }
                //兼容新版天转月
                if (isset($v['borrow_duration']) && $v['borrow_duration']) {
                    if (isset($v['product_type']) && $v['product_type'] == 6) {
                        $data[$k]['borrow_duration_new'] = $v['borrow_duration'] . '个月';
                    } else {
                        $data[$k]['borrow_duration_new'] = ceil($v['borrow_duration'] / 30) . '个月';
                    }
                }

                $repayment_type = isset(FieldKey::$borrow_info_repayment_type[$v['repayment_type']]) ? FieldKey::$borrow_info_repayment_type[$v['repayment_type']] : '';
                $data[$k]['repayment_type_name'] = $repayment_type;

                if (isset($v['schedular_time'])) $data[$k]['schedular_time'] = date('Y-m-d', strtotime($v['schedular_time']));

                if (isset($v['second_verify_time']))
                    $v['second_verify_time'] = $v['second_verify_time'] > 0 ? $data[$k]['second_verify_time'] = date('Y-m-d H:i:s', $v['second_verify_time']) : '';

                if (isset($v['deadline']) && !empty($v['deadline'])) $data[$k]['deadline'] = date('Y-m-d H:i:s', $v['deadline']);
                if (isset($v['first_verify_time']) && !empty($v['first_verify_time'])) $data[$k]['first_verify_time'] = date('Y-m-d H:i:s', $v['first_verify_time']);

                if (isset($v['has_borrow']) && !empty($v['has_borrow'])) {
                    $data[$k]['progress'] = number_format(substr(sprintf('%.3f', ($v['has_borrow'] / $v['borrow_money'] * 100)), 0, -1), 2, '.', '');

                    if ($data[$k]['progress'] > 100 || $data[$k]['progress'] == 100.00) $data[$k]['progress'] = 100;
                }

                $data[$k]['wan_interest'] = 0;

                if (in_array($v['repayment_type'], [1, 4])) {

                    $data[$k]['wan_interest'] = number_format(($v['borrow_interest_rate'] * 10000 * $v['borrow_duration'] / 36000), 2, '.', '');
                }
                if (in_array($v['repayment_type'], [2, 3])) {

                    $cur_num = ceil($v['borrow_duration'] / 30);
                    $cur_rem = $v['borrow_duration'] % 30;
                    if ($cur_num < 1) $cur_num = 1;

                    $cur_mon = number_format(10000 / $cur_num, 2, '.', '');
                    $investor_interest_4_one = $investor_interest_4_two = 0;
                    for ($ks = 1; $ks <= $cur_num; $ks++) {
                        $investor_interest_4_one = number_format($cur_rem * $v['borrow_interest_rate'] * 10000 / 36000, 2);
                        $interest_money = number_format((10000 - ($ks - 1) * $cur_mon) * $v['borrow_interest_rate'] * 30 / 36000, 2, '.', '');
                        $investor_interest_4_two += ($ks == 1 ? 0 : $interest_money);
                    }

                    $data[$k]['wan_interest'] = $investor_interest_4_one + $investor_interest_4_two;
                } elseif ($v['repayment_type'] == 5) {
                    $params = array(
                        'month_times' => isset($v['repayment_type_expand']) ? $v['repayment_type_expand'] : 0,
                        'account' => 10000,
                        'year_apr' => $v['borrow_interest_rate'],
                        'borrow_time' => isset($v['first_deadline']) ? $v['first_deadline'] : 0,
                        'type' => 'all',
                        'cur_time' => strtotime(date('Y-m-d', time())),
                    );
                    //计算获取总利息
                    $inverest_result = WjzxBorrow::EqualBeforeIAfterC($params);
                    $data[$k]['wan_interest'] = isset($inverest_result['interest']) ? getFloatValue($inverest_result['interest'], 2) : 0;
                    $data[$k]['remaining_time'] = 0;
                }

                if (isset($v['updata']) && $v['updata']) {
                    $data[$k]['updata'] = unserialize($v['updata']);
                    if (isset($data[$k]['updata']) && $data[$k]['updata']) {
                        $img_list = [];
                        foreach ($data[$k]['updata'] as $sub_k => $sub_v) {
                            array_push($img_list, [
                                'img' => str_replace(config('aliyun_oss.oss_url'), config('aliyun_oss.static_url'), $sub_v['img']),
                                'info' => $sub_v['info'],
                            ]);
                        }
                        $data[$k]['updata'] = $img_list;
                    }
                }
                if (isset($v['borrow_info'])) $data[$k]['borrow_info'] = nl2br($v['borrow_info']); //按照横排排列
                if (isset($v['risk_tips'])) $data[$k]['risk_tips'] = nl2br($v['risk_tips']); //按照横排排列
            }
        }
        return $data;
    }

    /**
     * 委托类型
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getTrustStatusNameAttr($value, $data)
    {
        return isset(FieldKey::$borrow_info_trust_status[$data['type']]) ? FieldKey::$borrow_info_trust_status[$data['type']] : '';
    }

    public function getSchedularTimeAttr($value, $data)
    {
        if (isset($data['schedular_time'])) return date('Y-m-d', strtotime($data['schedular_time']));
    }

    //获取微财富列表
    public function index_borrow_list($page, $limit)
    {
        $field = 'id,has_borrow,borrow_money,borrow_duration,borrow_interest_rate,repayment_type,borrow_status,remaining_time,product_type,borrow_tps, pro_provide, borrow_times, borrow_min, borrow_max,borrow_duration';
        $borrow = $this->getBorrowList(array('borrow_status' => array('IN', '2,4,6'), 'product_type' => array('IN', '1,2,4,5,6'), 'is_publish' => 1), $field, 'borrow_status, first_verify_time DESC, second_verify_time DESC, id DESC', $page, $limit)->toArray();

        if ($page == 1) {
            $new_borrow = $this->getBorrowTpsList(['borrow_status' => ['IN', [2, 4, 6]], 'borrow_tps' => 3, 'is_publish' => 1], $field, 'borrow_status ASC,id DESC', 0, 1)->toArray();

            /* $new_borrow = $db->getBorrowList(array(
                 'borrow_status' => array('IN', '2'),
                 'borrow_tps' => 2, 'is_publish' => 1
             ), $field, 'id DESC', 0, 1)->toArray();*/

            if (!empty($new_borrow)) {
                $new_borrow = array_pop($new_borrow);
                foreach ($borrow as $k => $v) {
                    if ($v['id'] == $new_borrow['id']) {
                        unset($borrow[$k]);
                        break;
                    }
                }
                array_unshift($borrow, $new_borrow);
            }
        }

        foreach ($borrow as $key => $val) {
            if ($val['product_type'] != 6) {
                $borrow[$key]['borrow_duration'] = ceil($val['borrow_duration'] / 30);
            }
            $borrow[$key]['borrow_status_name'] = isset(FieldKey::$borrow_info_borrow_status[$val['borrow_status']]) ? FieldKey::$borrow_info_borrow_status[$val['borrow_status']] : '';
        }
        return $borrow;
    }

    //惠学贷列表
    public function student_loan($page, $limit)
    {
        $field = 'id,has_borrow,borrow_money,borrow_duration,borrow_interest_rate,repayment_type,borrow_status,remaining_time,product_type,borrow_tps, pro_provide, borrow_times, borrow_min, borrow_max';

        $borrow = $this->getBorrowList(array('borrow_status' => array('IN', '2,4,6'), 'product_type' => 6), $field, 'borrow_status, first_verify_time DESC', $page, $limit);

        return $borrow;
    }

}